<template>
	<div class="contentmenu" id="avue-data-menu">
		<div class="contentmenu__item" @click="handleLock()">
			<i :class="activeComps && activeComps.length > 0 ? (activeComps[0].isLock ? 'el-icon-unlock' : 'el-icon-lock') : 'el-icon-lock'"></i>
			{{ activeComps && activeComps.length > 0 ? (activeComps[0].isLock ? '解锁' : '锁定') : '锁定' }}
		</div>
		<div class="contentmenu__item" @click="handleRelieve()" v-if="isRelieve">
			<i class="el-icon-close"></i>
			解组
		</div>
		<div class="contentmenu__item" @click="handlePublish()">
			<i class="el-icon-s-promotion"></i>
			发布
		</div>
		<div class="contentmenu__item" @click="handleDel()">
			<i class="el-icon-delete"></i>
			删除
		</div>
		<div class="contentmenu__item" @click="handleCopy()">
			<i class="el-icon-document-copy"></i>
			复制
		</div>
		<div class="contentmenu__item" @click="handleRename()">
			<i class="el-icon-edit"></i>
			重命名
		</div>
		<div class="contentmenu__item" @click="handlePaste()" v-if="copyCompObj">
			<i class="el-icon-document-copy"></i>
			粘贴
		</div>
		<div class="contentmenu__item" @click="handleStepTop()"><i class="el-icon-top"></i>上移</div>
		<div class="contentmenu__item" @click="handleStepBottom()"><i class="el-icon-bottom"></i>下移</div>
		<div class="contentmenu__item" @click="handleTop()"><i class="el-icon-upload2"></i>置顶</div>
		<div class="contentmenu__item" @click="handleBottom()"><i class="el-icon-download"></i>置底</div>
		<!-- <div class="contentmenu__item" @click="handleBluePrint">
            <i class="el-icon-s-grid"></i>导出到蓝图编辑器
        </div> -->
		<!--<div class="contentmenu__item">
            <small style="font-size: 10px">Tip:按空格可以拖拽画布</small>
        </div> -->
		<!-- 发布组件 -->
		<el-dialog title="发布组件" :visible.sync="dialogPublishFormVisible" :append-to-body="true" :close-on-click-modal="false" custom-class="publish-comp-dialog">
			<avue-form v-model="publishForm" :option="publishOption" @submit="publishSubmit" @error="error"
				><template slot-scope="{}" slot="componentJson">
					<monaco-editor v-model="publishForm.componentJson" height="400" language="json"></monaco-editor>
				</template>
				<template slot-scope="{}" slot="thumbnail">
					<el-upload
						ref="upload"
						list-type="picture"
						class="upload-demo"
						:on-success="handleThumbnailSuccess"
						:action="basePrefix + '/visual/put-file'"
						:on-remove="handleThumbnailRemove"
						:file-list="fileList"
						:limit="1"
					>
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</template>
			</avue-form>
		</el-dialog>
	</div>
</template>

<script>
import { createFile, uuid } from '@/utils/utils';
import MonacoEditor from '@/page/components/editor';
import { mapState, mapGetters } from 'vuex';
import { addComp } from '@/api/componentList';
import { basePrefix } from '@/config';
export default {
	name: 'contentmenu',
	components: {
		MonacoEditor
	},
	inject: ['contain'],
	data() {
		return {
			basePrefix: basePrefix,
			copyCompObj: null,
			dialogPublishFormVisible: false,
			publishForm: {
				thumbnail: ''
			},
			fileList: [],
			publishOption: {
				labelWidth: 100,
				column: [
					{
						label: '组件名称',
						prop: 'name',
						span: 12,
						rules: [
							{
								required: true,
								message: '请输入组件名称',
								trigger: 'blur'
							}
						]
					},
					{
						label: '组件类型',
						prop: 'componentType',
						type: 'select',
						dicData: [
							{
								label: '基础组件',
								value: 'BASE'
							},
							{
								label: '自定义组件',
								value: 'CUSTOMIZED'
							},
							{
								label: '业务组件',
								value: 'BUSINESS'
							}
						],
						span: 12,
						rules: [
							{
								required: true,
								message: '请输入组件类型',
								trigger: 'blur'
							}
						]
					},
					{
						label: '功能分类',
						prop: 'classify',
						type: 'select',
						dicData: [
							{
								label: '图表',
								value: 'CHART'
							},
							{
								label: '表单',
								value: 'FORM'
							},
							{
								label: '媒体',
								value: 'MEDIA'
							},
							{
								label: '指标',
								value: 'TARGET'
							},
							{
								label: '表格',
								value: 'TABLE'
							},
							{
								label: '其它',
								value: 'OTHER'
							}
						],
						span: 12,
						rules: [
							{
								required: false,
								message: '请输入组件类型',
								trigger: 'blur'
							}
						]
					},
					{
						label: '发布人',
						prop: 'publisher',
						span: 12,
						rules: [
							{
								required: false,
								message: '请输入发布人',
								trigger: 'blur'
							}
						]
					},
					{
						label: '缩略图上传',
						prop: 'thumbnail',
						formslot: true,
						span: 24
					},

					{
						label: '组件json',
						prop: 'componentJson',
						// type: "textarea",
						span: 24,
						// minRows: 10,
						// maxRows: 20,
						rules: [
							{
								required: true,
								message: '请输入组件json',
								trigger: 'blur'
							}
						]
					}
				]
			}
		};
	},
	computed: {
		...mapState({
			activeComps: state => state.activeComps,
			compsList: state => state.compsList
		}),
		...mapGetters(['activeCompsIndex']),
		isRelieve() {
			if (this.activeComps && this.activeComps[0] && this.activeComps[0].children) {
				return true;
			} else {
				return false;
			}
		}
	},
	methods: {
		handleThumbnailRemove() {
			this.fileList = [];
			this.$set(this.publishForm, 'thumbnail', '');
		},
		handleThumbnailSuccess(res) {
			if (res && res.code == 200) {
				let url = res.data.link;
				this.fileList = [
					{
						name: this.publishForm.name,
						url: url
					}
				];
				this.$set(this.publishForm, 'thumbnail', url);
			}
		},
		resetZindex(data) {
			data.map((c, i) => {
				c.zIndex = i + 1;
			});
		},
		//文件夹成组逻辑
		handleCompose() {},
		//文件夹解散逻辑
		handleRelieve() {
			if (this.activeComps && this.activeComps[0] && this.activeComps[0].children) {
				let { index, children, left, top } = this.activeComps[0];
				children.forEach(child => {
					child.left = child.oldLeft;
					child.top = child.oldTop;
					delete child.oldLeft;
					delete child.oldTop;
				});
				this.$parent.$refs.container.hideArea();
				this.$store.commit('clearCanvasCompList', [index]); // 删除成组组件
				this.$store.commit('clearActiveComps'); // 清除选中组件
				this.$store.commit('setCanvasCompsList', children); // 设置解组组件
			}
		},
		// 发布组件
		handlePublish() {
			let activeComps = JSON.parse(JSON.stringify(this.activeComps[0]));
			//  成组组件发布
			if (activeComps && activeComps.children && activeComps.children.length > 0) {
				activeComps.children.forEach(comp => {
					comp.left = comp.oldLeft;
					comp.top = comp.oldTop;
				});
			}
			this.dialogPublishFormVisible = true;
			this.publishForm.name = activeComps.name;
			this.publishForm.componentType = 'BASE';
			this.publishForm.classify = 'CHART';
			this.publishForm.publisher = '';
			this.fileList = [];
			this.publishForm.componentJson = JSON.stringify(activeComps, null, 2);
			html2canvas(document.getElementById('item' + activeComps.index), {
				useCORS: true,
				backgroundColor: null,
				allowTaint: true
			}).then(canvas => {
				function dataURLtoFile(dataurl, filename) {
					var arr = dataurl.split(','),
						mime = arr[0].match(/:(.*?);/)[1],
						bstr = atob(arr[1]),
						n = bstr.length,
						u8arr = new Uint8Array(n);
					while (n--) {
						u8arr[n] = bstr.charCodeAt(n);
					}
					return new File([u8arr], filename, { type: mime });
				}
				var file = dataURLtoFile(canvas.toDataURL('image/jpeg', 0.1), new Date().getTime() + '.jpg');
				var formdata = new FormData();
				formdata.append('file', file);
				axios
					.post(this.basePrefix + '/visual/put-file', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						const data = res.data.data;
						const url = data.link;
						this.fileList.push({
							name: this.publishForm.name,
							url: url
						});
						this.$set(this.publishForm, 'thumbnail', url);
					})
					.catch(err => {
						console.log(err);
						this.$message.error('组件封面更新失败，请检查服务端配置');
					});
			});
		},
		publishSubmit(form, done) {
			addComp(form)
				.then(() => {
					this.$message.success('组件发布成功！');
					this.dialogPublishFormVisible = false;
					this.$refs.upload.clearFiles();
					done();
				})
				.catch(() => {
					done();
				});
		},
		//删除组件的方法
		handleDel() {
			this.$confirm(`是否删除${this.activeComps[0].name} 组件?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.compsList.forEach(ele => {
						const { itemList, itemIndex } = this.contain.findnav(this.activeCompsIndex[0]);
						itemList.splice(itemIndex, 1);
					});
					this.$store.commit('clearActiveComps');
				})
				.catch(() => {});
		},
		//复制组件的方法 - 仅支持单个组件的复制
		handleCopy() {
			if (!this.activeCompsIndex.length) {
				this.copyCompObj = null;
				this.$message.warning('请先选择画布中的组件！');
				return;
			}
			let compInfo = this.compsList.filter(comp => comp.index == this.activeCompsIndex[0]);
			if (compInfo && compInfo.length > 0) {
				this.copyCompObj = this.deepClone(compInfo[0]);
			}
			this.$message.success('复制成功！');
		},
		// 粘贴
		handlePaste() {
			if (!this.copyCompObj) {
				this.$message.warning('请先选择组件进行复制！');
				return false;
			}
			let pasteData = this.deepClone(this.copyCompObj);
			let index = uuid();
			pasteData.left += 20;
			pasteData.top += 20;
			pasteData.name = pasteData.name;
			pasteData.index = index;
			if (pasteData.children) {
				pasteData.menu = false;
				pasteData.children.forEach(ele => (ele.index = uuid()));
			}
			this.copyCompObj = this.deepClone(pasteData);
			this.compsList.unshift(pasteData);
			this.$store.commit('clearActiveComps');
			this.$emit('handleContentmenu', {
				type: 'handlePaste',
				compsIndex: this.activeCompsIndex
			});
			// this.contain.clearActiveAllComps(); // 清除复制出来的激活组件
		},
		// 上移
		handleStepTop() {
			if (this.activeComps[0].zIndex == this.compsList.length - 1) {
				this.$message.warning(`当前组件${this.activeComps[0].name}已处于最高层级！`);
				return false;
			} else {
				let { itemList, itemIndex } = this.contain.findnav(this.activeCompsIndex[0]);
				let obj = itemList.splice(itemIndex, 1)[0];
				itemList.splice(itemIndex - 1, 0, obj);
			}
			this.$emit('handleContentmenu', {
				type: 'handleStepTop',
				compsIndex: this.activeCompsIndex
			});
		},
		// 下移
		handleStepBottom() {
			if (this.activeComps[0].zIndex == 0) {
				this.$message.warning(`当前组件${this.activeComps[0].name}已处于最低层级！`);
				return false;
			} else {
				let { itemList, itemIndex } = this.contain.findnav(this.activeCompsIndex[0]);
				let obj = itemList.splice(itemIndex, 1)[0];
				itemList.splice(itemIndex + 1, 0, obj);
			}
			this.$emit('handleContentmenu', {
				type: 'handleStepBottom',
				compsIndex: this.activeCompsIndex
			});
		},
		// 置顶
		handleTop() {
			if (this.activeComps[0].zIndex == this.compsList.length - 1) {
				this.$message.warning(`当前组件${this.activeComps[0].name}已处于最高层级！`);
				return false;
			} else {
				let { itemList, itemIndex } = this.contain.findnav(this.activeCompsIndex[0]);
				let obj = itemList.splice(itemIndex, 1)[0];
				itemList.unshift(obj);
			}
			this.$emit('handleContentmenu', {
				type: 'handleTop',
				compsIndex: this.activeCompsIndex
			});
		},
		// 置底
		handleBottom() {
			if (this.activeComps[0].zIndex == 0) {
				this.$message.warning(`当前组件${this.activeComps[0].name}已处于最低层级！`);
				return false;
			} else {
				let { itemList, itemIndex } = this.contain.findnav(this.activeCompsIndex[0]);
				let obj = itemList.splice(itemIndex, 1)[0];
				itemList.push(obj);
			}
			this.$emit('handleContentmenu', {
				type: 'handleBottom',
				compsIndex: this.activeCompsIndex
			});
		},
		handleRename() {
			this.$parent.handleReCompName();
		},
		// 锁定，解锁
		handleLock() {
			this.compsList.forEach(ele => {
				if (ele.index == this.activeCompsIndex[0]) {
					ele.isLock = !ele.isLock;
					this.activeComps[0].isLock = !this.activeComps[0].isLock;
					// if (ele.children) {
					//     ele.children.forEach((e) => {
					//         e.isLock = ele.isLock;
					//     });
					// }
					this.$store.commit('setActiveComps', {
						isKeysCtrl: false,
						...this.activeComps[0]
					});
				}
			});
			// this.$store.commit("clearActiveComps");
		},
		// 导出到蓝图
		handleBluePrint() {
			let compInfo = this.activeComps.map(comp => {
				return {
					index: comp.index,
					icon: comp.icon,
					name: comp.name,
					eventConfig: comp.eventConfig
				};
			})[0];
			console.log('compInfo', compInfo);
			// let cacheCompList = JSON.parse(
			//     localStorage.getItem("dvp-lt-compList") || "[]"
			// );
			if (cacheCompList.length == 0) {
				// localStorage.setItem(
				//     "dvp-lt-compList",
				//     JSON.stringify([compInfo])
				// );
			} else {
				let find = cacheCompList.find(comp => comp.index == compInfo.index);
				if (!find) {
					cacheCompList.push(compInfo);
					// localStorage.setItem(
					//     "dvp-lt-compList",
					//     JSON.stringify(cacheCompList)
					// );
				}
			}
		}
	}
};
</script>

<style>
.contentmenu {
	width: 200px;
	display: none;
	z-index: 99999;
	list-style: none;
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	padding: 0;
	background: #27343e;
	color: #bcc9d4;
}
.contentmenu__item {
	z-index: 10000;
	list-style: none;
	padding: 8px 12px;
	cursor: pointer;
	position: relative;
	font-size: 12px;
}
.contentmenu__item:hover {
	background-color: rgba(0, 192, 222, 0.1);
}
.contentmenu__item i {
	margin-right: 5px;
}
.contentmenu__item :first-child {
	padding-top: 5px;
}
.publish-comp-dialog {
	margin-top: 5vh !important;
}
</style>
